let urlBase = getApp().globalData.urlBase
let auth = require('./auth.js')
function httpGet(url, params, callBack) {
  let session = wx.getStorageSync('JSESSIONID')
  wx.request({
    url: urlBase + url,
    method: 'GET',
    data: params,
    header: {
      "content-type": "application/json",
      "Cookie": session
    },
    success: function (res) {
      if (res.data.code == 4444) {
        // 登录过期 重新登录
        auth.login(() => {
          wx.showToast({
            title: '请再试一次!',
            icon: 'none',
            duration: 1500,
            mask:true
          })
          wx.navigateBack()
        })
        return;
      }
      callBack(res.data);
    },
    fail: function (error) {
      console.log(error)
    }
  })
}

function httpPost(url, params, callBack) {
  let session = wx.getStorageSync('JSESSIONID')
  wx.request({
    url: urlBase + url,
    method: 'POST',
    data: json2Form(params),
    header: {
      "content-type": "application/x-www-form-urlencoded",
      "Cookie": session
    },
    success: function (res) {
      if (res.data.code == 4444) {
        // 登录过期 重新登录
        auth.login(() => {
          wx.showToast({
            title: '请再试一次!',
            icon: 'none',
            duration: 1500,
            mask:true
          })
          wx.navigateBack()
        })
        return;
      }
      callBack(res.data);
    },
    fail: function (error) {
      console.log(error)
    }
  })
}

function json2Form(json) {
  var str = [];
  for (var p in json) {
  str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&");
}

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatDate(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return [year, month, day].map(formatNumber).join('-') 
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
    httpGet: httpGet,
    httpPost: httpPost,
    formatTime: formatTime,
    formatDate: formatDate
}
